package com.yps.io.aio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncServerHandler implements Runnable {
	public CountDownLatch latch;
	public AsynchronousServerSocketChannel channel;
	public AsyncServerHandler(int port) {
		try {
			//c 创建服务通道
			channel = AsynchronousServerSocketChannel.open();//单例创建？
			//绑定端口
			channel.bind(new InetSocketAddress(port));
			System.out.println("服务已经启动,端口号:" + port);
		} catch (Exception e) {
			try {
				channel.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		//CountdownLatch 初始化
		//他的作用：在完成一组正在执行的操作之前，允许当前的现场一直阻塞
		//此外，让现场在此阻塞，防止服务端执行完后退出
		//也可以使用while(true) + sleep
		//生产环境就不需要担心这个，因为服务端不会退出
		latch = new CountDownLatch(1);
		//接收客户端清楚并且处理
		channel.accept(this, new AcceptHandler());
		try {
			latch.await();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
